/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.jg.xz.park;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.aliyunocr.utils.HttpUtils;
import org.jeecg.modules.third.jg.report.freight.information.util.WebUtils;
import org.jeecg.modules.third.jg.xz.park.constant.XzIndustrialParkConstant;
import org.jeecg.modules.third.jg.xz.park.dto.*;
import org.jeecg.modules.third.jg.xz.park.dto.payment.XzPaymentDTO;
import org.jeecg.modules.third.jg.xz.park.dto.resp.XzApiBaseResDTO;
import org.jeecg.modules.third.jg.xz.park.dto.shippingnote.XzShippingNoteDTO;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产业园
 *
 * @author duanlikao
 * @created 2022/6/9
 */
@Service
@Slf4j
public class XzIndustrialParkService {

    private static final Logger LOGGER = LoggerFactory.getLogger(XzIndustrialParkService.class);

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Value(value = "${yuanqu-report-platform.domain:}")
    private String YUANQU_API_DOMIAN ;// "https://dzhxm.95155.com:4430/xzyq";

    @Value(value = "${yuanqu-report-platform.username:}")
    private String YUANQU_API_USERNAME ;

    @Value(value = "${yuanqu-report-platform.password:}")
    private String YUANQU_API_PASSWORD;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取Token
     * @return
     */
    public String getToken(){

        //产业园平台
        if (!HyCfgUtil.isUsed2("yuanqu_report")){
            throw new JeecgBootException("园区监管平台未配置参数");
        }

        if (StrUtil.isEmpty(YUANQU_API_DOMIAN) || StrUtil.isEmpty(YUANQU_API_USERNAME) || StrUtil.isEmpty(YUANQU_API_PASSWORD)) {
            log.error("园区监管平台参数配置错误， {} {} {}", YUANQU_API_DOMIAN, YUANQU_API_USERNAME, YUANQU_API_PASSWORD);
            throw new JeecgBootException("园区监管平台参数配置错误");
        }

        Object tokenObject  = redisUtil.hasKey(XzIndustrialParkConstant.XZINDUSTRIALPARKAPI_TOKEN_KEY) ?
                redisUtil.get(XzIndustrialParkConstant.XZINDUSTRIALPARKAPI_TOKEN_KEY) : null;

        String token = StringUtils.EMPTY;
        if (tokenObject == null ) {

            String digestPwd = DigestUtils.sha1Hex(this.YUANQU_API_PASSWORD);
            String url =  this.YUANQU_API_DOMIAN;
            String path = "/platform/login/login";
            Map <String, String> headers = new HashMap <>();
            //根据API的要求，定义相对应的Content-Type
            headers.put("Content-Type", "application/json; charset=UTF-8");

            Map <String, String> querys = new HashMap <>();
            JSONObject requestObj = new JSONObject();
            requestObj.put("loginAccount", YUANQU_API_USERNAME);
            requestObj.put("loginPwd", digestPwd);
            // 拼装请求body的json字符串
            String bodys = requestObj.toString();

            try {
                HttpResponse response = HttpUtils.doPost(url, path, "POST", headers, querys, bodys);
                int stat = response.getStatusLine().getStatusCode();
                if (stat == 200) {
                    String res = EntityUtils.toString(response.getEntity(),"utf-8");
                    log.info("getToken res_obj:{} ", res);
                    XzApiBaseResDTO resDTO = JSONObject.parseObject(res, XzApiBaseResDTO.class);
                    if (1001 == resDTO.getStatus() &&  resDTO.isSuccess()) {
                       String result  = resDTO.getResult().toString() ;
                       JSONObject resultJSONObject = JSONObject.parseObject(result);
                       token =  resultJSONObject.getString("token") != null ?  resultJSONObject.getString("token") : StringUtils.EMPTY;
                        if(StringUtils.isNotBlank(token)){
                            redisUtil.set(
                                    XzIndustrialParkConstant.XZINDUSTRIALPARKAPI_TOKEN_KEY,
                                    token,
                                    XzIndustrialParkConstant.XZINDUSTRIALPARKAPI_TOKEN_KEY_EXPIRE
                            );
                            return token;
                        }
                    }else{
                        throw new JeecgBootException("产业园服务获取token失败，请稍后重试。" + resDTO.getMessage());
                    }

                } else {
                    log.info("getToken Http code: {}  | http header error msg:{} | Http body error msg: ", stat,
                            response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
                    throw new JeecgBootException("产业园服务获取token失败，请稍后重试。");
                }
            } catch (Exception e) {
                log.info("getToken url:{} bodys:{}", url + path, bodys);
                log.info("getToken Exception :{} ", e.getMessage());
                throw new JeecgBootException("获取token失败: " + e.getMessage());
            }
        }
        return tokenObject != null && StringUtils.isNotEmpty(tokenObject.toString())
                ? tokenObject.toString() : token;
    }

    /**
     * 业务通用请求
     * @param path
     * @param DTO
     * @return
     */
    public XzApiBaseResDTO postDTO( String path, Object DTO){
        //产业园平台
        if (!HyCfgUtil.isUsed2("yuanqu_report")){
            throw new JeecgBootException("园区监管平台未配置参数!");
        }

        XzApiBaseResDTO resDTO = new XzApiBaseResDTO();
        if(DTO== null){
            resDTO.setMessage("提交数据不能为空！");
            return resDTO;
        }

        String token = getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            resDTO.setMessage("产业园服务获取token失败,请稍后重试。");
            return resDTO;
        }
        String url = this.YUANQU_API_DOMIAN;
        Map <String, String> headers = getHeaders(token);
        Map<String, String> querys = new HashMap<>();
        String bodys = JSONObject.toJSONString(DTO);
        log.info("园区上报请求 -> {} - {}", url  + path, bodys);
        try {
            HttpResponse response = HttpUtils.doPost(url,  path, "POST", headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat == 200){
                String res = EntityUtils.toString(response.getEntity(),"utf-8");
               log.info("园区上报回执 <- {} ",res);
                resDTO = JSONObject.parseObject(res, XzApiBaseResDTO.class);
            }else{
                log.info("园区上报回执 Http code: {}  | http header error msg: {} | Http body error msg: {}",
                        stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));

                resDTO.setMessage("HTTP请求失败！" + stat);
            }
        } catch (Exception e) {
            log.info("园区上报异常 {} ", e.getMessage());
            resDTO.setMessage("操作失败！" + e.getMessage());

        }
        return resDTO;
    }

    /**
     * 文件上传接口
     * 上传电子运单、车辆信息、驾驶员信息中相关图片文件(备注:文件大小需要小于2M)
     * @param file
     * @return
     */
    public String uploadFile(String file, String desc){
        log.info("园区上传文件地址:{}" ,file);
        //产业园平台
        if (!HyCfgUtil.isUsed2("yuanqu_report")){
            throw new JeecgBootException("园区监管平台未配置参数!");
        }

        String token = getToken();
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("产业园服务获取token失败,请稍后重试。");
        }
        // uploadpath + File.separator +
        String wholefile =  file;
        File files = new File(wholefile);
        if (!files.exists()) {
            log.info("产业园 uploadFiles exists:{}" ,wholefile);
            throw new JeecgBootException("园区上传文件失败: " + desc + "文件不存在。");
        }
        long length = files.length() / 1024;
        if (length > 1024*2){
            throw new JeecgBootException(desc + "文件大小不能超过2M");
        }

        String domain = this.YUANQU_API_DOMIAN;
        String path = "/platform/file/uploadImage";
        Map<String, String> headers  = getHeaders(token);
//        log.info("uploadFile url :{} file:{}", XZIP_API_DOMIAN +  path, wholefile);
        try {
            String url =  domain +  path;
//            String result = WebUtils.uploadImg2XZ(url, new File(wholefile), headers);
            String result = WebUtils.uploadImg(url, new File(wholefile), headers);
            log.info(result);
//            log.info("uploadFile result :{}  file:{}", result, wholefile);
            if(StringUtils.isNotEmpty(result)){
                XzApiBaseResDTO resDTO = JSONObject.parseObject(result, XzApiBaseResDTO.class);
//                log.info("uploadFile resDTO :{}  file:{}", resDTO, wholefile);
                if(1001 == resDTO.getStatus() && resDTO.isSuccess()){
                    return resDTO.getResult().toString();
                }

            }
        } catch (Exception e) {
            log.info("uploadFile Exception :{} file:{}",e.getMessage(), wholefile);
            throw new JeecgBootException("产业园服务上传文件失败:"+e.getMessage()+",请稍后重试。");
        }
        return StringUtils.EMPTY;
    }


    /**
     * 业务接口认证公共头部
     * @param token
     * @return
     */
    private Map <String, String> getHeaders(String token){
        Map<String, String> headers = new HashMap <>();
        headers.put("token",  token);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        headers.put("User-Agent", "Mozilla/4.76");
        return headers;
    }

    /**
     * 驾驶员基本信息上报接口
     * @param driverDTO
     * @return
     */
    public XzApiBaseResDTO subjectDriver(XzDriverDTO driverDTO) {
        return postDTO("/platform/api/v1/driver", Collections.singletonList(driverDTO));
    }

    /**
     * 实际承运人基本信息上报接口
     * @param carrierDTO
     * @return
     */
    public XzApiBaseResDTO subjectCarrier(JSONObject carrierDTO) {
        return postDTO("/platform/api/v1/carrier/report", Collections.singletonList(carrierDTO));
    }

    /**
     * 实际承运人承运人关联车辆
     * @param carrierDTO
     * @return
     */
    public XzApiBaseResDTO subjectCarrierVehicle(JSONObject carrierDTO) {
        return postDTO("/platform/api/v1/carrier/bind/vehicle", Collections.singletonList(carrierDTO));
    }

    /**
     * 承运人关联驾驶员
     * @param carrierDTO
     * @return
     */
    public XzApiBaseResDTO subjectCarrierDriver(JSONObject carrierDTO) {
        return postDTO("/platform/api/v1/carrier/bind/driver", Collections.singletonList(carrierDTO));
    }

    /**
     * 车辆基本信息上
     * 报接口
     * @param vehicleDTO
     * @return
     */
    public XzApiBaseResDTO subjectVehicle(XzVehicleDTO vehicleDTO){
        return postDTO("/platform/api/v1/vehicle", Collections.singletonList(vehicleDTO));
    }

    /**
     * 上传运单
     * @param xzShippingNoteDTO
     * @return
     */
    public XzApiBaseResDTO waybillShippingNote(XzShippingNoteDTO xzShippingNoteDTO){
        return postDTO("/platform/api/v1/transport", Collections.singletonList(xzShippingNoteDTO));
    }
    /**
     * 上传资金流水
     * @param paymentDTO
     * @return
     */
    public XzApiBaseResDTO waybillPayment(XzPaymentDTO paymentDTO){
        return postDTO("/platform/api/v1/money", Collections.singletonList(paymentDTO));
    }

    /**
     * 驾驶员信息校验结
     * 果查询接口
     * @param ValidateDriverDTOS
     * @return
     */
    public XzApiBaseResDTO validateDriver(List<ValidateDriverDTO>  ValidateDriverDTOS){
        return postDTO("/platform/api/v1/driver/validate", ValidateDriverDTOS);
    }


    /**
     * 承运人信息校验结
     * 果查询接口
     * @param ValidateCarrierDTOS
     * @return
     */
    public XzApiBaseResDTO validateCarrier(List<ValidateCarrierDTO>  ValidateCarrierDTOS){
        return postDTO("/platform/api/v1/carrier/validate", ValidateCarrierDTOS);
    }


    /**
     * 车辆信息校验结
     * 果查询接口
     * @param ValidateVehicleDTOS
     * @return
     */
    public XzApiBaseResDTO validateVehicle(List<ValidateVehicleDTO>  ValidateVehicleDTOS){
        return postDTO("/platform/api/v1/vehicle/validate", ValidateVehicleDTOS);
    }



    /**
     * 运单校验结果查询接口
     * @param transportValidateParamDTOS
     * @return
     */
    public XzApiBaseResDTO validateTransport(List<TransportValidateParamDTO> transportValidateParamDTOS){
        return postDTO("/platform/api/v1/transport/validate", transportValidateParamDTOS);
    }

    /**
     * 运单申诉接口
     * @param appealDTO
     * @return
     */
    public XzApiBaseResDTO transportAppeal(AppealDTO appealDTO){
        return postDTO("/platform/api/transport/appeal", appealDTO);
    }

    /**
     * 运单申诉结果查询接口
     * @param appealDTO
     * @return
     */
    public XzApiBaseResDTO transportAppealQuery(AppealDTO appealDTO){
        return postDTO("/platform/api/transport/appeal/query", appealDTO);
    }

    public static void main(String[] args) {
        XzIndustrialParkService a =  new  XzIndustrialParkService();
        //String b = a.getToken();
        //System.out.println(b);
        //90ec2b3f-aa86-49fb-9168-0c973ccacfb9.jpeg
        //case_model.png
        String b =  a.uploadFile("/Users/duanlikao/Downloads/11111.jpeg", "测试");
        System.out.println(b);

    }



}
